package server

import (
	"fmt"
	"html/template"
	"net/http"
	"strconv"
	"time"

	"appengine"
	"appengine/datastore"
	"appengine/user"
)

type Greeting struct {
	Author  string
	Content string
	Date    time.Time
}

func init() {
	http.HandleFunc("/", root)
	http.HandleFunc("/hand", hand)
}

// guestbookKey returns the key used for all guestbook entries.
func guestbookKey(c appengine.Context) *datastore.Key {
	// The string "default_guestbook" here could be varied to have multiple guestbooks.
	return datastore.NewKey(c, "Guestbook", "default_guestbook", 0, nil)
}

func root(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)

	u := requireLogin(ctx, r, w)
	if u == nil {
		return
	}
	fmt.Fprintf(w, bboTemplate)
}

func requireLogin(ctx appengine.Context, r *http.Request, w http.ResponseWriter) *user.User {
	u := user.Current(ctx)
	if u != nil {
		return u
	}
	url, err := user.LoginURL(ctx, r.URL.String())
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return nil
	}
	w.Header().Set("Location", url)
	w.WriteHeader(http.StatusFound)
	return nil
}

const bboTemplate = `
<html>
  <head>
    <title>Go BridgeHand</title>
  </head>
  <body>
    <form action="/hand" method="post">
      <div>Deal: <input name="deal" type="text"></input></div>
      <div>Table: <input name="table" type="text"></input></div>
      <div>Auction: <input name="auction" type="text"></input></div>
      <div>North: <input name="north" type="text"></input></div>
      <div>East: <input name="east" type="text"></input></div>
      <div>South: <input name="south" type="text"></input></div>
      <div>West: <input name="west" type="text"></input></div>
      <div><input type="submit" value="Show Link"></div>
    </form>
  </body>
</html>
`

func hand(w http.ResponseWriter, r *http.Request) {
	ctx := appengine.NewContext(r)
	u := requireLogin(ctx, r, w)
	if u == nil {
		return
	}

	i, err1 := strconv.Atoi(r.FormValue("deal"))
	if err1 != nil {
		http.Error(w, err1.Error(), http.StatusInternalServerError)
		return
	}
	deal := GetDealInfo(i)

	hand := fmt.Sprintf("?b=%d&v=%s&d=%s&a=%s&n=%s&e=%s&s=%s", deal.Number, deal.Vul, deal.Dealer,
		r.FormValue("auction"),r.FormValue("north"),r.FormValue("east"),r.FormValue("south"))

	err := handTemplate.Execute(w, hand)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
	}
}

const handTemplateHtml = `
<html>
  <head>
    <title>Go BridgeHand</title>
  </head>
  <body>
    <iframe height="600" width="600" 
      src="http://www.bridgebase.com/tools/handviewer.html{{.}}">
    </iframe>
  </body>
</html>
`

var handTemplate = template.Must(template.New("hand").Parse(handTemplateHtml))

//ok

func sign(w http.ResponseWriter, r *http.Request) {
	c := appengine.NewContext(r)
	g := Greeting{
		Content: r.FormValue("content"),
		Date:    time.Now(),
	}
	if u := user.Current(c); u != nil {
		g.Author = u.String()
	}
	// We set the same parent key on every Greeting entity to ensure each Greeting
	// is in the same entity group. Queries across the single entity group
	// will be consistent. However, the write rate to a single entity group
	// should be limited to ~1/second.
	key := datastore.NewIncompleteKey(c, "Greeting", guestbookKey(c))
	_, err := datastore.Put(c, key, &g)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	http.Redirect(w, r, "/", http.StatusFound)
}
